<script setup>
import { ref, computed, onMounted } from 'vue';
import { Cell as VanCell, List as VanList, Search as VanSearch, Button as VanButton } from 'vant';
import { useRouter } from 'vue-router';
import { useClusterStore } from '@/stores/cluster';
import { getProjectPage } from '@/api/dolphin'; // 引入API

const router = useRouter();
const clusterStore = useClusterStore();

// 定义响应式变量
const searchQuery = ref('');
const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 计算属性用于获取当前集群信息
const currentClusterInfo = computed(() => clusterStore.currentCluster);

// 计算属性用于过滤搜索结果
const filteredItems = computed(() =>
  items.value.filter(item => item.name.toLowerCase().includes(searchQuery.value.toLowerCase()))
);

// 模拟初始数据加载
onMounted(() => {
  onSearch();
});

// 定义方法
const onSearch = async () => {
  try {
    // 重置分页和加载状态
    currentPage.value = 1;
    items.value = [];
    loading.value = true;
    finished.value = false;

    const response = await getProjectPage(currentClusterInfo.value.id, currentPage.value, pageSize.value);
    
    items.value = response.records || [];
    
    // 如果返回的结果少于请求的数量，则认为已经没有更多数据了
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }

    loading.value = false;
  } catch (error) {
    console.error('搜索项目失败:', error);
    loading.value = false;
  }
};

const onCancel = () => {
  searchQuery.value = '';
  // 清除搜索结果并重置状态
  items.value = [];
  loading.value = false;
  finished.value = false;
};

const onLoad = async () => {
  if (finished.value) return; // 如果已经完成加载，则不执行加载更多

  try {
    currentPage.value++;
    const response = await getProjectPage(currentClusterInfo.value.id, currentPage.value, pageSize.value);
    items.value.push(...(response.records || []));

    // 当加载的数据达到总数量时，设置 finished 为 true
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }
  } catch (error) {
    console.error('加载更多项目失败:', error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};
</script>


<template>
  <div>
    <van-search
      v-model="searchQuery"
      placeholder="搜索项目"
      show-action
      @search="onSearch"
      @cancel="onCancel"
    >
      <template #action>
        <van-button type="primary" size="small" round @click="onSearch">搜索</van-button>
      </template>
    </van-search>

    <van-list
      class="list-container"
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell 
        v-for="item in filteredItems" 
        :key="item.id" 
        :title="item.name" 
        :to="{
          name: 'DolphinMenu',
          params: { projectCode: item.code }
        }" 
      />
    </van-list>

  </div>
</template>

<style scoped>
</style>